import { captureScreen, captureRef } from 'react-native-view-shot'
import RNFS from 'react-native-fs'
import RNFetchBlob from 'rn-fetch-blob'

export async function shareScreenshot(mainViewRef) {
	try {
        const captureConfig = {
          format: 'png',
          quality: 0.7,
          // result: Platform.OS==='ios'? 'data-uri':'base64',
          // result: 'tmpfile',
          result: 'base64',
          width: 750,
        }
        let imgBase64 = ''
        try {
          imgBase64 = await captureScreen(captureConfig)
        } catch (e) {
          try {
            imgBase64 = await captureRef(mainViewRef.current, captureConfig)
          } catch (ex) {
            throw ex
          }
        }
        const screenShotShowImg = `data:image/png;base64,${imgBase64}`;
        saveImage(screenShotShowImg);
      } catch (e) {
        Alert.alert(`截图失败，请稍后再试${e.toString()}`)
        console.log(e)
      } finally {
      }
}

function saveImage () {
	console.log('图片保存中...');
     if (IS_IOS) {
        CameraRoll.saveToCameraRoll(screenShotShowImg).then((result) => {
          Toast.showShortCenter(`保存成功！地址如下：\n${result}`);
        }).catch((error) => {
          Toast.showShortCenter(`保存失败！\n${error}`);
        });
      } else {
      //调用该方法是 对 截屏的图片进行拼接，仅限Android端拼接，IOS的我不会，切此处的base64Img是未进行拼接‘data:image/png;base64’字段的base64图片格式
      // await NativeModules.UtilsModule.contactImage(base64Img).then((newImg) => {
      //   // console.log('path====', newImg);
      //   const screenShotShowImg = `data:image/png;base64,${newImg}`;
      //
      // }, (ex) => {
      //   console.log('ex====', ex);
      // });
        //不经过拼接直接保存到相册
        this.saveForAndroid(screenShotShowImg, (result) => {
          Toast.showShortCenter(`保存成功！地址如下：\n${result}`);
        }, () => {
          Toast.showShortCenter('保存失败！');
        });
      }
}